using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.WorkOrders.Commands;

/// <summary>
/// 关闭工单命令。
/// </summary>
/// <param name="WoId"></param>
public sealed record CloseWorkOrderCommand(long WoId) : IRequest<IResult<bool>>;

internal sealed class CloselWorkOrderCommandHandler(IRepository<ProdWorkOrder> repo) : IRequestHandler<CloseWorkOrderCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CloseWorkOrderCommand request, CancellationToken cancellationToken)
    {
        var workOrder = await repo.GetByIdAsync(request.WoId, cancellationToken);
        if (workOrder == null)
        {
            return Result.Failure("未找到要更新的工单");
        }

        if (workOrder.Status is not WoStatusEnum.Completed and not WoStatusEnum.Cancelled)
        {
            return Result.Failure("工单只有在已完工或取消状态才能关闭");
        }

        workOrder.ChangeStatus(WoStatusEnum.Closed);
        workOrder.Priority = 0; // 关闭单据，优先级重置
        var ok = await repo.UpdateAsync(workOrder, m => new
        {
            m.Priority,
            m.LastStatus,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
